<template>
	<view class="product">
		
		<scroll-view scroll-y="true">
			<HeaderNav bgcolor='#56677c' text='产品' :showNavBackBtn='true' color='#fff'></HeaderNav>
			<view v-if="gid == -1" class="title">添加产品</view>
			<view v-else class="title">修改产品</view>
			<view class="content">
				<form @submit="onSubmit">
					<!-- 产品编号 -->
					<van-field
					  class="ttt"
					  :value="pid"
					  :name="pid"
					  label="产品编号"
					  placeholder="请输入产品编号"
					  @change="onChangePid"
					  required='true'
					  :rules="[{ required: true, message: '请输入产品编号' }]"
					/>
					
					<view class="box">
						<view class="box-item">
							<!-- 产品重量 -->
							<van-field
							  :value="weight"
							  :name="weight"
							  label="重量"
							  placeholder="输入重量"
							  required='true'
							  :disabled='weightDisabled'
							  @change="onChangeWeight"
							  :rules="[{ required: true, message: '请输入产品重量' }]"
							/>
							<view>g</view>
						</view>
						<view class="box-item">
							<!-- 产品数量单位 -->
							<van-field
							  :value="unit"
							  :name="unit"
							  label="单位"
							  placeholder="输入单位"
							  required='true'
							  @change="onChangeUnit"
							  :rules="[{ required: true, message: '请输入产品单位' }]"
							/>
						</view>
					</view>
					
					<!-- 产品简称 -->
					<van-field
					  :value="sname"
					  :name="sname"
					  label="简称"
					  placeholder="请输入产品简称"
					  @change="onChangeSname"
					  required='true'
					  :rules="[{ required: true, message: '请输入产品简称' }]"
					/>
					
					<!-- 产品全称 -->
					<van-field
					  :value="fname"
					  :name="fname"
					  label="全称"
					  v-module="fname"
					  placeholder="请输入产品全称"
					  @change="onChangeFname"
					  :rules="[{ required: true, message: '请输入产品全称' }]"
					/>
					
					<!-- 产品描述 -->
					<van-field
					  :value="desc"
					  :name="desc"
					  label="描述"
					  type="textarea"
					  autosize
					  placeholder="请输入产品描述"
					  @change="onChangeDesc"
					  :rules="[{ required: true, message: '请输入产品重量' }]"
					/>
					<!-- 是否丝织品 -->
					<!-- <van-radio-group :value="radio">
					  <van-cell-group>
					    <van-cell title="丝织品" clickable data-name="1">
					      <van-radio  data-name="0" name="0" label-disabled="false">是&nbsp;&nbsp;</van-radio>
						  <van-radio slot="right-icon" data-name="1" name="1" >否</van-radio>
					    </van-cell>
					  </van-cell-group>
					</van-radio-group> -->
					
					<view class="line">
						<!-- 尺寸大小 -->
						<view class="combox">
							<!-- <van-cell-group> -->
							  <van-cell title="尺寸大小" clickable data-name="1">
								<view class="uni-form-item uni-column">
									<picker @change="bindPickerChange" :range="array">
										<label class="" v-model="name">{{array[index]}}</label>
									</picker>
								</view>
							  </van-cell>
							<!-- </van-cell-group> -->
						</view>
						
						<!-- 产品种类 -->
						<view class="combox">
							<!-- <van-cell-group> -->
							  <van-cell title="产品种类" clickable data-name="1">
							    <view class="uni-form-item uni-column">
							    	<picker @change="bindPickerChange1" :range="categoryArr">
							    		<label class="" v-model="categoryName">{{categoryArr[categoryIndex]}}</label>
							    	</picker>
							    </view>
							  </van-cell>
							<!-- </van-cell-group> -->
						</view>
					</view>
					
					<view class="sss">
						<ImgTest ref="phototList"></ImgTest>
						<view v-show="record" class="clear" @click="clearInfo">清空排产</view>
					</view>
					
					
					
					<view class="js">
						<view class="mid">
							<view class="info">
								填写纤维和百分比(*)
							</view>
							<view class="mid-container">
								<view class="info-box">
									<view class="ccc">*</view>
									<view class="weight-input">
										<view class="uni-form-item uni-column">
											<picker @change="bindPickerChange2" class="combox" :range="fiberArr">
												<label class="" v-model="fiberName">{{ fiberArr[fiberIndex] }}</label>
											</picker>
										</view>
									</view>
									<view class="ttt">
										<view class="iconfont icon-xiangxia ic"></view>
									</view>
								</view>
								<view class="info-box">
									<view class="ccc">*</view>
									<input	class="weight-input" placeholder="例如: 80" v-model.number="percent" />
									<view class="kkk">
										%
									</view>
								</view>
								<view class="ccc">*</view>
								<view class="add" @click="add">+</view>
							</view>
						</view>
					
						
						<view class="list">
							<view class="list-top">
								添加
							</view>
						</view>
						<view class="list" v-for='(item, index) in listAdd' :key="index">
							<view class="list-container">
								<view class="content1">
									<span>{{ item.name1 }}</span>
									<span>{{ item.per }}%</span>
									<span>{{ item.weight1 }}g</span>
								</view>
								<view class="del" @click="del(index)">
									<view class="iconfont icon-jianhao dd"></view>
								</view>
							</view>
						</view>
					</view>
					
					<view class="foot" @click="createGood" v-if="submitDisabled">
						<button class="submit" >提交</button>
					</view>
					
				</form>
				<!-- <Material></Material> -->
			</view>
			
		</scroll-view>
	</view>
</template>

<script>
	import HeaderNav from '@/common/HeaderNav/HeaderNav'
	import ImgTest from './components/ImgTest'
	
	import { addGoods as addGoodsApi } from '@/api/goods'
	import { getGoods as getGoodsApi, updGoods as upGoodsApi } from '@/api/goods'
	import { getRecord as getRecordApi, clearRecord as clearRecordApi } from '@/api/emission'

	export default {
		data() {
			return {
				checked: f,
				weightDisabled: false,
				submitDisabled: false,
				cid: 0,
				radio: '1',
				index: 0,
				array: ["XS","S","M","L","XL","XXL","均码"],
				name: "XS",
				categoryArr: ["男装","女装","中性"],
				categoryIndex: 0,
				categoryName: '男装',
				fiberArr: [
					'蚕丝',
					'涤纶',
					'氨纶',
					'棉花',
					'粘胶',
					'亚克力',
					'聚酰胺',
					'聚丙烯',
					'羊毛',
					'亚麻',
					'皮革',
					'其他面料'
				],
				fiberFac: [ 
					0.709570,
					-0.021330,
					-0.021330,
					-0.027680,
					-0.030140,
					-0.038430,
					-0.024350,
					-0.019790,
					-0.046280,
					-0.015000,
					-0.147000,
					-0.027600
				],
				fiberIndex: 0,
				fiberName: '蚕丝',
				fac: 0,
				percent: '',
				ss: 0,
				listAdd: [],
				carbon: 0.1,
				material: '',
				pid: '',
				sname: '',
				weight: '',
				fname: '',
				silk: '',
				size: '',
				category: '',
				image: '',
				images: '',
				desc: '',
				mid: 0,
				phototList: [],
				gid: -1,
				unit: '',
				record: false
			}
		},
		methods: {
			async createGood() {
				this.size=this.name
				this.category=this.categoryName
				this.material=this.enMaterial(this.listAdd)
				
				// 计算carbon
				let sum = 0;
				this.listAdd.forEach(function(element, index, array) {
					sum=sum+element.fac*element.weight1
					// console.log('1: ',element.fac*element.weight1)
				});
				// console.log('carbon:',parseFloat(sum).toFixed(2))
				this.carbon=parseFloat(sum).toFixed(2)
				
				// 检查必填是否为空
				if(!this.checkEmpty()) {
					// return;
				}
				
				if(this.$refs.phototList.phototList.length == 0) {
					console.log('没有上传图片')
					this.image=''
				}else {
					// console.log('图片',this.$refs.phototList.phototList[0].url)
					this.image=this.$refs.phototList.phototList[0].url
				}
				
				if(this.unit=='' || this.unit==null) {
					this.unit='件'
				}
				
				// console.log(this.pid, this.sname, this.fname, this.weight, this.desc, this.size, this.category,
				// this.material, this.image, this.carbon)
				
				
				if(this.gid == -1) { // 调用添加产品接口
					const data = {
						cid: this.cid,
						material: this.material,
						pid: this.pid,
						unit: this.unit,
						sname: this.sname,
						fname: this.fname,
						weight: this.weight,
						carbon: this.carbon,
						fname: this.fname,
						silk: this.silk,
						size: this.size,
						category: this.category,
						image: this.image,
						desc: this.desc
					}
				
					const res = await addGoodsApi(data)
					// console.log(res)
					if(res.status != this.API_STATUS_CODE.SUCCESS) {
						uni.showToast({
							icon: 'success',
							title: '添加产品成功',
							duration: 3000
						})
						
						clearTimeout(this.timer); //清除延迟执行 
						  
						this.timer = setTimeout(()=>{  //设置延迟执行
							uni.switchTab({
								url: '../../pages/management/management'
							})
						},3000);
						
						
					}else {
						uni.showToast({
							icon: 'error',
							title: '添加产品失败，请刷新重试',
							duration: 3000
						})
					}
				}else { // 调用修改产品接口
					
				
					if(this.$refs.phototList.phototList[0] == null) {
						this.image=this.images
					}
					const data1 = {
						gid: this.gid,
						material: this.material,
						pid: this.pid,
						unit: this.unit,
						sname: this.sname,
						fname: this.fname,
						weight: this.weight,
						carbon: this.carbon,
						fname: this.fname,
						silk: this.silk,
						size: this.size,
						category: this.category,
						image: this.image,
						desc: this.desc
					}
					
					const res = await upGoodsApi(data1)
					// console.log(res)
					if(res.status === this.API_STATUS_CODE.SUCCESS) {
						uni.showToast({
							icon: 'success',
							title: '修改产品成功',
							duration: 3000
						})
						
						clearTimeout(this.timer); //清除延迟执行
						  
						this.timer = setTimeout(()=>{  //设置延迟执行
							uni.switchTab({
								url: '../../pages/management/management'
							})
						},3000);
					}else {
						uni.showToast({
							icon: 'error',
							title: '修改产品失败，请刷新重试',
							duration: 3000
						})
					}
				}
				
				
				
			},
			async __getGoods() {
				const data = {
					gid: this.gid
				}
				
				const res = await getGoodsApi(data)
				const goods = res.data
				if(res.status != this.API_STATUS_CODE.SUCCESS) {
					uni.showToast({
						icon: 'none',
						title: '获取产品信息失败',
						duration: 3000
					})
				}else {
					// console.log(res.data)
					this.pid=goods.pid
					this.material=goods.material
					this.sname=goods.shortName
					this.fname=goods.fullName
					this.weight=goods.weight
					this.carbon=goods.carbon
					this.silk=goods.hasSilk
					this.category=goods.category
					this.unit=goods.unit
					this.image=goods.imageURL
					this.images=goods.imageURL
					this.desc=goods.description
					this.name=goods.size
					this.phototList=goods.imageURL
					
					this.deMaterial(this.material)
					this.submitDisabled=true
					
					// 获取尺寸的下标
					for(let i=0; i<this.array.length; i++) {
						if(this.name == this.array[i]) {
							this.index=i;
							break;
						}
						// console.log(this.array[i])
					}
					
					// 获取种类的下标
					for(let i=0; i<this.categoryArr.length; i++) {
						if(this.category == this.categoryArr[i]) {
							this.categoryIndex=i;
							this.categoryName=this.category;
							break;
						}
						// console.log(this.array[i])
					}
					
				}
				
			},
			async __getRecord() {
				const data={
					cid: this.cid,
					gid: this.gid
				}
				
				const res=await getRecordApi(data)
				this.record=(res.status==1)
				console.log('res,',this.record)
			},
			async clearInfo() {
				// console.log('666')
				const data={
					cid: this.cid,
					gid: this.gid
				}
				
				const res=await clearRecordApi(data)
				// console.log(res)
				if(res.status != 0) {
					this.record=false
					uni.showToast({
						icon: 'success',
						title: '清除该产品排产成功',
						duration: 3000
					})
				}
			},
			checkEmpty() {
				if(this.cid==-1 || this.material=='' || this.pid=='' || this.weight==0 || this.sname=='') {
					uni.showToast({
						title: '请填写完整数据',
						icon: 'none',
						duration: 2000
					})
					return false
				}
			},
			enMaterial(materialArr){
			    let materialine = "";
			    for (let mt of materialArr)
			        materialine += mt.mid + '_' + mt.per + ';';
			    return materialine;
			},
			deMaterial(materialine){
			    let crude = materialine.slice(0, -1).split(';');
			    let materialArr = [];
			    for (let item of crude){
			        let inr = item.indexOf('_');
			        let mid = Number(item.substr(0, inr));
			        let per = Number(item.substr(inr + 1, item.length));
					this.fac=this.fiberFac[mid];
					this.weight1=parseFloat(this.weight*per/100).toFixed(1);
					this.percent=per;
					this.fiberIndex=mid;
					this.fiberName=this.fiberArr[mid];
					this.add();
					// console.log('name1: '+this.fiberName);
			        materialArr.push({"mid":mid, "per":per});
			    }
			    return materialArr;
			},
			bindPickerChange: function(e) { // 大小
				this.index = e.target.value			//将数组改变索引赋给定义的index变量
				this.jg=this.array[this.index]		//将array【改变索引】的值赋给定义的jg变量
				this.name=this.array[this.index]
				// console.log("籍贯为0：",this.index)		//输出获取的籍贯值，例如：中国
			},
			bindPickerChange1: function(e) { // 种类
				this.categoryIndex = e.target.value			//将数组改变索引赋给定义的index变量
				this.jg=this.categoryArr[this.categoryIndex]		//将array【改变索引】的值赋给定义的jg变量
				this.categoryName=this.categoryArr[this.categoryIndex]
				// console.log("籍贯为1：",this.categoryIndex)		//输出获取的籍贯值，例如：中国
			},
			bindPickerChange2: function(e) { // 材质
				//console.log('picker发送选择改变，携带值为', e.target.value)   用于输出改变索引值
				this.fiberIndex = e.target.value			//将数组改变索引赋给定义的index变量
				this.jg=this.fiberArr[this.fiberIndex]	//将array【改变索引】的值赋给定义的jg变量
				this.fiberName=this.fiberArr[this.fiberIndex]
				this.fac=this.fiberFac[this.fiberIndex]
				// console.log("籍贯为1：",this.fiberIndex)		//输出获取的籍贯值，例如：中国
			},
			add() {
				// console.log(this.weight, this.fiberName, this.percent, this.fac)
				if(this.weight-0==0 || this.fiberName=='' || this.percent==0) {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'error'
					})
					return
				}
				let s = 0;
				this.listAdd.forEach(function(element, index, array) {
					s += element.per;
					// console.log(element.name1, element.fac)
				});
				
				if (this.percent + s > 100) {
					let tt=100-s
					uni.showToast({
						title: '百分比不能大于100%',
						icon: 'error',
						duration: 2000
					})
					return
				}
				this.ss=s
				// console.log(this.s);
				// console.log(this.weight, this.name, this.percent)
				// console.log(this.fiberName, this.percent, this.fiberIndex, this.fac)
				let obj={
					name1: this.fiberName,
					per: this.percent,
					mid: this.fiberIndex,
					fac: this.fac,
					weight1: parseFloat(Number(this.weight)*this.percent/100).toFixed(1)
				}
				console.log('per: '+this.per)
				console.log('weight: '+Number(this.weight))
				console.log('weight1: '+ obj.weight1)
				if(this.percent + s == 100) {
					this.submitDisabled=true
				}
				
				this.listAdd.push(obj)
				// console.log(this.listAdd)
				this.weightDisabled=true
			},
			del(index) {
				this.listAdd.splice(index,1)
				if(this.listAdd.length == 0) {
					this.weightDisabled=false
				}
				if(this.ss != 100) {
					this.submitDisabled=false
				}
			},
			onSubmit() {
				console.log(this.sname)
				uni.request({
			   
				})
			},
			onChangePid(event){
				// console.log(event)
				this.pid=event.detail
			},
			onChangeDesc(event){
				// console.log(event)
				this.desc=event.detail
			},
			onChangeWeight(event){
				// console.log(event)
				this.weight=event.detail
				// console.log(this.weight)
			},
			onChangeSname(event){
				this.sname=event.detail
			},
			onChangeFname(event) {
				this.fname=event.detail
			},
			onChangeUnit(event) {
				this.unit=event.detail
				// console.log(this.unit)
			},
		},
		onLoad(options) {
			// 修改产品 获取产品编号
			const gid = JSON.parse(options.gid)
			this.gid = gid
			// console.log(gid)
			
			this.cid=this.$store.getters.getUser.cid
			if(this.cid==null || this.cid==0) {
				uni.navigateTo({
					url: '../login/login'
				})
			}else {
				if(gid != -1) { // 调用获取产品信息接口
					this.__getGoods()
					this.__getRecord()
				}
			}
		},
		components: {
			HeaderNav,
			ImgTest,
			// Material
		}
	}
</script>

<style lang="less" scoped>
	scroll-view {
		box-sizing: border-box;
		padding-top: 44rpx;
		
		padding-bottom: 40rpx;
		// background: linear-gradient(0deg, #021B79, #0b2997, #254dd3);
		background: linear-gradient(to top,#172349,#1d2e55,#203f5f,#4f5e72);
		// background: linear-gradient(to top,#1d2e55,#203f5f,#4f5e72,#68819a);
	}
	
	.product {
		width: 100%;
		
		
		.title {
			margin: 20rpx;
			margin-top: 40rpx;
			font-size: 38rpx;
			color: #fff;
		}
		
		.content {
			height: 100vh;
			font-size: 40rpx!important;
			box-sizing: border-box;
			
			.box {
				width: 100%;
				display: flex;
				align-items: flex-end;
				justify-content: space-between;
				text-align: left;
				// padding: 20rpx;
				box-sizing: border-box;
				
				.box-item {
					position: relative;
					width: 50%;
					
					view {
						position: absolute;
						top: 13rpx;
						right: 7rpx;
						color: #fff;
						font-size: 35rpx;
					}
				}
				
				
			}
			
			// .box:first-child {
			// 	width: 40%;
			// }
			
			.ttt {
				font-size: 70rpx!important;
			}
			
			.line {
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.combox {
					width: 50%;
				}
			}
			
			.sss {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-right: 100rpx;
				
				.clear {
					width: 50%;
					height: 100rpx;
					line-height: 100rpx;
					font-size: 40rpx;
					text-align: center;
					color: #fff;
					z-index: 999;
					border-radius: 80rpx;
					box-sizing: border-box;
					background-color: #1989fa;
				}
			}
			
			.mid {
				width: 100%;
				// color: rgba(255, 255, 255, .9);
				font-size: 32rpx;
				// margin: 20rpx auto;
				margin-top: 20rpx;
				text-align: center;
				box-sizing: border-box;
				
				.info {
					color: #fff;
					font-size: 38rpx;
					text-align: left;
					margin-left: 20rpx;
				}
				
				.ccc {
					position: absolute;
					top: -30rpx;
					left: 0rpx;
					color: red;
				}
				
				
			
				.mid-container {
					display: flex;
					align-items: flex-end;
					justify-content: space-between;
					text-align: center;
					padding: 20rpx;
					box-sizing: border-box;
			
					.info-box {
						position: relative;
						background-color: #ffffff;
						margin-top: 30rpx;
						margin-right: 10rpx;
						height: 80rpx;
						width: 40%;
						border-radius: 10rpx;
						box-sizing: border-box;
						// border-radius: 1px solid #000!important;
			
						.weight-input {
							position: absolute;
							top: 19rpx;
							left: 23rpx;
							display: inline-block;
							width: 55%;
							text-align: left;
							font-size: 37rpx;
							color: #1e3358;
							
							.combox {
								width: 300rpx;
							}
							
						}
			
						.ttt {
							position: absolute;
							display: inline-block;
							width: 22%;
							top: 0rpx;
							right: 0rpx;
							color: #808487;
							height: 100%;
							font-size: 40rpx;
							line-height: 80rpx;
							border-top-right-radius: 10rpx;
							border-bottom-right-radius: 10rpx;
			
							.ic {
								font-size: 74rpx!important;
							}
						}
						
						.kkk {
							position: absolute;
							display: inline-block;
							width: 22%;
							top: 0rpx;
							right: 0rpx;
							color: #1e3358;
							height: 100%;
							font-size: 40rpx;
							line-height: 80rpx;
							border-top-right-radius: 10rpx;
							border-bottom-right-radius: 10rpx;
							border-left: 1px solid #999;
							background-color: #e8ecef;
						}
					}
			
					.add {
						box-sizing: border-box;
						width: 15%;
						height: 80rpx;
						font-weight: 700;
						font-size: 60rpx;
						line-height: 70rpx;
						color: #fff;
						border-radius: 10rpx;
						background-color: #1989fa;
					}
				}
			}
			
			.list {
				// height: 130rpx;
				padding: 0 20rpx;
				box-sizing: border-box;
				
				.list-top {
					background-color: #ffffff;
					width: 100%;
					height: 100%;
					padding: 20rpx;
					text-align: left;
					box-sizing: border-box;
					box-sizing: 999;
					font-weight: 700;
					font-size: 37rpx;
					border-bottom: 1px solid #999;
				}
				
				.list-container {
					display: flex;
					align-items: center;
					justify-content: space-between;
					background-color: #ffffff;
					width: 100%;
					height: 100%;
					padding: 20rpx;
					font-size: 38rpx;
					box-sizing: border-box;
					border-bottom: 1px solid #999;
					
					.content1 {
						width: 77%;
						span {
							margin-right: 20rpx;
						}
						
					}
					.del {
						
						width: 20%;
						height: 60rpx;
						color: #ffffff;
						line-height: 60rpx;
						border-radius: 10rpx;
						background-color: #ca444b;
						
						.dd {
							text-align: center;
							font-weight: 700;
							font-size: 40rpx!important;
						}
					}
				}
			}
		
			.foot {
				padding: 40rpx 0;
				box-sizing: border-box;
				
				.submit{
					width: 95%;
					height: 100rpx;
					font-size: 40rpx;
					text-align: center;
					color: #fff;
					z-index: 999;
					border-radius: 80rpx;
					box-sizing: border-box;
					background-color: #1989fa;
				}
			}
			
		}
	}
	
</style>